<template>
  <div class="content_box">
    <div class="headerContent">
      <el-input
        v-model="listQuery.keyword"
        placeholder="请输入工号/姓名/手机号"
        style="width: 200px"
        clearable
        @input="defaultList()"
        @keyup.enter.native="getListDate()"
      ></el-input>
      <el-button type="primary" class="filter-item" @click="getListDate()"
        >搜索</el-button
      >
      <el-button type="primary" class="filter-item" @click="handleAdd"
        >新增</el-button
      >
    </div>
    <el-table :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="工号" align="center" width="200" fixed>
        <template slot-scope="{ row }">
          <span>{{ row.workNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.departmentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职位" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职位" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系手机号" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.adminStatus === 1 ? "启用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="340px">
        <template slot-scope="{ row, $index }">
          <el-button
            type="primary"
            size="mini"
            @click="handleStatus(row, $index)"
            >{{ row.adminStatus === 1 ? "禁用" : "启用" }}</el-button
          >
          <el-button type="success" size="mini" @click="handleCode(row)"
            >老师推广码</el-button
          >
          <el-button type="success" size="mini" @click="handleUpdate(row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(row, $index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="dialogTitle"
      :visible.sync="isShowDialog"
      @close="$refs['form'].clearValidate()"
      width="800px"
    >
      <el-form ref="form" :model="form" label-width="130px" :rules="formRules">
        <label class="basicInfo">基本信息</label>
        <el-form-item label="头像" :required="true">
          <el-upload
            action="#"
            list-type="picture-card"
            accept=".jpg, .jpeg, .png, .JPG, .JPEG"
            :http-request="handleAvatar"
            :before-upload="beforeAvatarUpload"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :auto-upload="false"
            :class="{ hide: hideUpload }"
            :file-list="imgsList"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input
            v-model="form.realName"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="毕业院校" prop="graduationSchool">
          <el-input
            type="textarea"
            v-model="form.graduationSchool"
            placeholder="请输入毕业院校"
            clearable
          />
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-select
            v-model="form.education"
            placeholder="请选择类型"
            clearable
            class="filter-item"
            style="width: 140px"
          >
            <el-option
              v-for="item in global.educationList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-input
            v-model="form.label"
            style="width: 400px"
            type="text"
            autosize
            placeholder="例如:首席教师"
            clearable
          />
        </el-form-item>
        <el-form-item label="工作经历" prop="jobs">
          <el-input
            v-model="form.jobs"
            style="width: 400px"
            height="150px"
            type="textarea"
            :rows="6"
            placeholder="200字以内"
            :clearable="true"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="教育经历" prop="experiences">
          <el-input
            v-model="form.experiences"
            style="width: 400px"
            height="150px"
            type="textarea"
            :rows="6"
            placeholder="200字以内"
            :clearable="true"
            maxlength="200"
            show-word-limit
          />
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content">
              <span>1.2004年至今在XXX公立学校任教16年</span>
              <br />
              <span>2.2003年哈佛硕士</span>
              <br />
              <span>3.2001年北京本科</span>
            </div>
            <el-button type="text" style="color: black; margin-left: 10px"
              >帮助</el-button
            >
          </el-tooltip>
        </el-form-item>
        <label class="basicInfo">职能信息</label>
        <el-form-item label="所属部门" prop="departmentId">
          <el-select
            v-model="form.departmentId"
            placeholder="请选择类型"
            clearable
            class="filter-item"
            style="width: 140px"
          >
            <el-option
              v-for="item in departmentAllList"
              :key="item.id"
              :label="item.departName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="roleId">
          <el-select
            v-model="form.roleId"
            placeholder="请选择类型"
            clearable
            class="filter-item"
            style="width: 140px"
          >
            <el-option
              v-for="item in positionAllList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="身份" prop="isTeacher">
          <el-radio-group v-model="form.isTeacher">
            <el-radio label="0">非老师</el-radio>
            <el-radio label="1">老师</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工号" prop="workNo">
          <el-input
            v-model.number="form.workNo"
            placeholder="请输入工号"
            clearable
            autocomplete="off"
            @change="validRepeatWorkNum"
          />
          <i class="el-icon-check" v-if="isRegister == -1">通过</i>
          <i
            class="el-icon-close"
            v-if="isRegister !== -1 && isRegister !== null"
            >工号已存在</i
          >
        </el-form-item>
        <div v-if="form.isTeacher === '1'">
          <label class="basicInfo">资质信息</label>
          <el-form-item label="教学类型" prop="teachingType">
            <el-radio-group
              v-model="form.teachingType"
              @change="chooseTeachingType"
            >
              <el-radio label="1">兴趣教育</el-radio>
              <el-radio label="2">学科辅导</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="从教时间" prop="teachingTime">
            <el-date-picker
              v-model="form.teachingTime"
              type="date"
              placeholder="选择日期"
              value-format="timestamp"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="授课类型" prop="subjectType">
            <el-radio-group v-model="form.subjectType" class="shoukeType">
              <el-radio
                :label="item.id"
                v-for="item in subjectTypeList"
                :key="item.id"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="授课年级" v-if="form.teachingType === '2'">
            <el-checkbox-group v-model="form.grades">
              <el-checkbox
                :label="item.id"
                v-for="(item, index) in gradesList"
                :key="index"
                >{{ item.text }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="教学成果" prop="score">
            <el-input
              v-model="form.score"
              style="width: 400px"
              height="150px"
              type="textarea"
              :rows="6"
              placeholder="200字以内"
              :clearable="true"
              maxlength="200"
              show-word-limit
            />
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">
                <span>简单说明自己的教学成果,</span>
                <br />
                <span
                  >例如：中山大学博士生，热爱教学。耐心真诚，带领学生从生活中的点点滴滴领略数学的乐趣。</span
                >
                <br />
                <span
                  >数学学习过程中，从现象中寻找规律，由图形中简化问题，在理解中加深记忆。</span
                >
                <br />
                <span
                  >在数学的世界里，引导学生感悟生活，享受乐趣，开拓思维。或者指导学员获得过什么奖项</span
                >
              </div>
              <el-button type="text" class="helpTips">帮助</el-button>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="教学特点" prop="trait">
            <el-input
              v-model="form.trait"
              style="width: 400px"
              height="150px"
              type="textarea"
              :rows="6"
              placeholder="200字以内"
              :clearable="true"
              maxlength="200"
              show-word-limit
            />
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">
                <span
                  >例如：善于从生活现象切入主题，以加深学生对问题的理解。幽默风趣，情绪饱满，不失干练。</span
                >
              </div>
              <el-button type="text" class="helpTips">帮助</el-button>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="奖项证书">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-remove="handleRemovecertificateList"
              :on-change="handleChangecertificateList"
              :auto-upload="false"
              :file-list="certificateList"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label="教师风采">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-remove="handleRemovemomentList"
              :on-change="handleChangemomentList"
              :auto-upload="false"
              :file-list="momentList"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
        </div>
        <label class="basicInfo">账号信息</label>
        <el-form-item label="手机号">
          <el-input
            v-model="form.phone"
            placeholder="请输入员工的手机号"
            clearable

            @blur="validReoeatPhoneNum"
          />
          <i v-if="isPhoneNum == 1 && isPhoneNum !== null" class="el-icon-check"
            >通过</i
          >
          <i v-if="isPhoneNum == 2 && isPhoneNum !== null" class="el-icon-close"
            >电话已存在</i
          >
        </el-form-item>
        <el-form-item label="初始密码">
          <el-input
            v-model="form.password"
            :placeholder="showInfo"

          />
        </el-form-item>
        <el-form-item>
          <el-button @click="isShowDialog = false">取消</el-button>
          <el-button type="primary" :loading="isLoading" @click="submit"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 裁剪框 -->
    <el-dialog
      title="裁剪图片"
      :visible.sync="cropper.dialog"
      width="600px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <div
        style="width: 516px; height: 624px; text-align: center; margin: 0 auto"
      >
        <VueCropper
          ref="cropper"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          :info="true"
          :full="option.full"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :original="option.original"
          :auto-crop="option.autoCrop"
          :fixed="option.fixed"
          :fixed-number="option.fixedNumber"
          :center-box="option.centerBox"
          :info-true="option.infoTrue"
          :fixed-box="option.fixedBox"
        />
      </div>
      <div slot="footer" class="dialog-footer footer">
        <el-button @click="handleRemove">取 消</el-button>
        <el-button type="primary" @click="confirmCropper">确定裁剪</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getListDate()"
    />
    <el-dialog
      :title="realNameTitle"
      :visible.sync="wxpromotionDialog"
      width="500px"
    >
      <el-image :src="qrCodeUrl" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="wxpromotionDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import md5 from 'js-md5'
import * as Employee from '@/api/system'
import { VueCropper } from 'vue-cropper'
import Pagination from '@/components/Pagination'
import mixinOptions from '@/views/system/mixin/emporymixin'
import { QRcode } from '@/api/system'
export default {
  name: 'EmployeeList',
  mixins: [mixinOptions],
  components: { Pagination, VueCropper },
  data() {
    return {
      listQuery: {
        keyword: '',
        pageSize: 10,
        currentPage: 1,
        departmentId: '',
        orgId: this.$store.getters.businessId,
      },
      list: null,
      total: 0,
      dialogTitle: '新增员工',
      orgId: this.$store.getters.businessId,
      isEdit: false,
      form: {
        avatar: '',
        departmentId: '', // 部门
        education: '', // 学历
        experiences: '', // 教育经历
        graduationSchool: '', // 毕业院校
        identity: 4, // 商户端后台员工
        isTeacher: '0', // 是否老师
        jobs: '', // 工作经历
        label: '', // 标签
        lat: '',
        lng: '',
        orgId: this.$store.getters.businessId,
        orgName: '',
        password: 'JBL123456',
        phone: '',
        realName: '',
        roleId: '', // 职位
        sex: '',
        workNo: '', // 工号
        // --------------------------
        teachingType: '1', // 教学类型 兴趣教育||学科辅导
        subjectType: '', // 授课类型
        teachingTime: '', // 从教时间
        score: '', // 教学成果
        trait: '', // 教学特点
        certificates: '', // 证书
        styles: '', // 风采
        grades: []
      },
      formRules: {},
      isRegister: null,
      isPhoneNum: null,
      editId: '',
      id: '',
      wxpromotionDialog: false,
      qrCodeUrl: '',
      realNameTitle:''
    }
  },
  mounted() {
    this.getListDate()
  },
  methods: {
    // 列表数据
    getListDate() {
      Employee.organizeEmployeeList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
      })
    },
    // 输入框搜索条件
    defaultList() {
      this.listQuery.currentPage = 1
      this.getListDate()
    },
    // 编辑员工
    handleUpdate(row) {
      this.dialogTitle = '编辑员工'
      this.getAllOptionsList()
      this.editId = row['userId']
      this.id = row.id
      this.gradesList = []
      for (const i in this.form) {
        this.form[i] = ''
      }
      this.isEdit = true
      this.form.identity = 4
      this.form.isTeacher = '0'
      this.form.orgId = this.$store.getters.businessId
      this.showInfo = '密码不可修改'
      this.form.teachingType = '1'
      this.form.grades = []
      this.imgsList = [],
      this.certificateList = []
      this.momentList = []
      this.getEmployeeDetail(row['userId']) // 位置不能换
    },
    // 新增员工
    handleAdd() {
      this.dialogTitle = '新增员工'
      this.isShowDialog = true
      this.getAllOptionsList()
      this.grades = []
      for (const i in this.form) {
        this.form[i] = ''
      }
      this.form.identity = 4
      this.form.isTeacher = '0'
      this.form.orgId = this.$store.getters.businessId
      this.form.password = 'JBL123456'
      this.form.teachingType = '1'
      this.form.grades = []
      this.imgsList = [],
        this.certificateList = []
      this.momentList = []
      this.isEdit = false
      this.$nextTick(() => {
        this.$refs['form'].clearValidate();
      })
    },
    // 兴趣/学科
    chooseTeachingType() {
      this.form.teachingType === '1' ? this.getSubjectList() : this.subjectTypeList = this.interestCourseList
      this.form.grades = []
      this.form.subjectType = ''
    },
    // 提交表单
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === '新增员工') {
            this.form.teachingType === '1' && this.isNoTeacherSubmit()
            this.form.teachingType === '2' && this.isTeacherSubmit()
          } else {
            this.form.teachingType === '1' && this.editIsNoTeacherSubmit()
            this.form.teachingType === '2' && this.editIsTeacherSubmit()
          }
        }
      })
    },
    // 非老师提交
    isNoTeacherSubmit() {
      const paramsList = { ...this.form }
      paramsList.password = md5(String(this.form.password)),
        paramsList.orgName = localStorage.getItem('businessName'),
        paramsList.lat = localStorage.getItem('businessLat'),
        paramsList.lng = localStorage.getItem('businessLng')
      paramsList.grades = this.form.grades.toString()
      Employee.organizeEmployeeAdd(paramsList).then(res => {
        this.successResponse()
      })
    },
    // 老师提交
    isTeacherSubmit() {
      const paramsList = { ...this.form }
      paramsList.grades = this.form.grades.toString()
      Employee.organizeEmployeeAdd(paramsList).then(res => {
        this.successResponse()
      })
    },
    // 编辑非老师提交
    editIsNoTeacherSubmit() {
      const paramsList = { ...this.form }
      paramsList.userId = this.editId
      paramsList.id = this.id
      paramsList.orgName = localStorage.getItem('businessName'),
      paramsList.lat = localStorage.getItem('businessLat'),
      paramsList.lng = localStorage.getItem('businessLng')
      paramsList.phone = ''
      paramsList.grades = this.form.grades.toString()
      console.log(paramsList);
      // return
      Employee.organizeEmployeeUpdate(paramsList).then(res => {
        this.successResponse()
      })
    },
    // 编辑老师提交
    editIsTeacherSubmit() {
      const paramsList = { ...this.form }
      paramsList.userId = this.editId
      paramsList.id = this.id
      paramsList.grades = this.form.grades.toString()
      paramsList.phone = ''
      Employee.organizeEmployeeUpdate(paramsList).then(res => {
        this.successResponse()
      })
    },
    // 提交成功信息
    successResponse() {
      this.$message({ message: '提交成功', type: 'success' })
      this.isShowDialog = false
      this.getListDate()
    },
    // 获取员工信息
    getEmployeeDetail(employeeId) {
      Employee.organizeEmployeeDetail({
        userId: employeeId,
        orgId: this.orgId
      }).then((response) => {
        const data = response.data
        this.form.teachingType = data.teachingType
        // 授课类型
        if (this.form.teachingType === '2') {
          console.log('学科辅导');
          Employee.subjectList().then((res) => {
            res.data.forEach((item, index) => {
              if (item.name.indexOf('学科辅导') !== -1) {
                this.subjectTypeList = item.categories
              }
            })
          })
        }
        // 头像回显
        if (data.avatar !== null && data.avatar !== '') {
          this.imgsList = [{ url: data.avatar }]
          this.form.avatar = data.avatar
          this.hideUpload = true
        }
        // 证书回显
        if (data.certificates !== '' && data.certificates !== null) {
          this.certificateList = []
          data.certificates.split(',').slice(0, data.certificates.split(',').length).forEach((item) => {
            this.form.certificates += item + ','
            this.certificateList.push({ url: item })
          })
          this.hideUpload = true
        }
        // 风采回显
        if (data.styles !== '' && data.styles !== null) {
          this.momentList = []
          data.styles.split(',').slice(0, data.styles.split(',').length).forEach((item) => {
            this.form.styles += item + ','
            this.momentList.push({ url: item })
          })
          this.hideUpload = true
        }
        this.isShowDialog = true
        const returnInfo = { ...data }
        returnInfo.sex = data.sex.toString()
        returnInfo.education = data.education.toString()
        if(data.departmentId!=null){
          returnInfo.departmentId = data.departmentId.toString()
        }
        returnInfo.isTeacher = data.isTeacher + ''
        returnInfo.subjectType = data.subjectType + ''
        returnInfo.grades = data.teachingType === '2' ? data.grades.split(',') : ''
        this.form = returnInfo
      })
    },
    async handleCode(row) {
      let { realName } = row
      this.realNameTitle = `${realName} 老师的推广码`
      const paramsObject = {
        id: row.userId,
        businessId: this.$store.getters.businessId,
        pagesPath: `pages/famousDetail/famousDetail`
      }
      const res = await QRcode(paramsObject)
      const data = res.data
      if (!data) return
      if (data instanceof Object) {
        this.qrCodeUrl = data.qrcodeImg
      } else {
        this.qrCodeUrl = data
      }
      this.wxpromotionDialog = true

    }
  }
}
</script>

<style scoped lang='scss'>
.content_box {
  padding: 15px;
  .headerContent {
    width: 100%;
    margin: 15px 0;
    .filter-item {
      margin: 0 10px;
    }
  }
  .basicInfo {
    width: 120px;
    height: 50px;
    line-height: 50px;
    font-size: 18px;
    text-align: right;
    display: block;
  }
  /deep/ .el-dialog__body {
    padding: 0 10px 10px 0;
  }
  .el-icon-check {
    margin-left: 10px;
    color: green;
  }
  .el-icon-close {
    margin-left: 10px;
    color: red;
  }
  .helpTips {
    color: black;
    margin-left: 10px;
  }
  .shoukeType {
    height: 60px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  /deep/.el-upload-list--picture-card /deep/.el-upload-list__item {
    width: 100px;
    height: 100px;
  }
  /deep/.el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 110px;
  }
  /deep/ .el-dialog__body , /deep/ .el-dialog__footer{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 15px;
  }
}
</style>